﻿using NHibernate;
using NHibernate.Context;
using NHibernate.Engine;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Shape.Mvp.Persistence.Conversations.Hibernate
{
	public class ThreadLocalConversationalSessionContext : ThreadLocalConversationContainer, ICurrentSessionContext
	{
		private readonly ISessionFactoryImplementor factory;

		public ThreadLocalConversationalSessionContext(ISessionFactoryImplementor factory)
		{
			this.factory = factory;
		}

		#region Implementation of ICurrentSessionContext

		public ISessionFactoryImplementor Factory
		{
			get { return factory; }
		}

		public ISession CurrentSession()
		{
			var c = CurrentConversation as HibernateConversation;
			if (c == null)
			{
				throw new InvalidOperationException("No current conversation available. Create a conversation and bind it to the container.");
			}
			return c.GetSession(Factory);
		}

		#endregion
	}
}
